Component({
  data: {
    selected: 0,
    color: "#999999",
    selectedColor: "#07c160",
    list: [{
      pagePath: "/pages/index/index",
      text: "首页",
      iconPath: "/assets/images/home.png",
      selectedIconPath: "/assets/images/home-active.png"
    }, {
      pagePath: "/pages/my/index",
      text: "我的",
      iconPath: "/assets/images/my.png",
      selectedIconPath: "/assets/images/my-active.png"
    }]
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset;
      const url = data.path;
      wx.switchTab({
        url,
        success: () => {
          this.setData({
            selected: data.index
          });
        }
      });
    }
  },
  lifetimes: {
    // 组件所在页面显示时
    attached() {
      try {
        // 获取当前页面路径
        const pages = getCurrentPages();
        // 增加安全检查，防止页面栈为空
        if (pages && pages.length > 0) {
          const currentPage = pages[pages.length - 1];
          if (currentPage && currentPage.route) {
            const url = '/' + currentPage.route;
            
            // 根据路径设置选中状态
            const list = this.data.list;
            const selected = list.findIndex(item => url.indexOf(item.pagePath.split('/').pop()) !== -1);
            
            if (selected !== -1) {
              this.setData({ selected });
            }
          }
        }
      } catch (err) {
        console.error('设置自定义导航栏状态时出错:', err);
        // 出错时默认选中第一个选项
        this.setData({ selected: 0 });
      }
    }
  }
}); 